package com.fofia.iotweb.framework.auth;

import cn.hutool.log.StaticLog;
import org.noear.solon.annotation.Component;
import org.noear.solon.auth.AuthException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.validation.ValidatorException;


@Component
public class SolonRouterInterceptor implements RouterInterceptor {
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        //此时：当 mainHandler == null 时，就是没有主处理。
        if(mainHandler == null){
            //如果不需要再继承，就可以当 404 处理并返回了
            ctx.redirect("/notFound");
            ctx.setHandled(true); //为了不被过滤器，误会。标为已处理
            return;
        }

        try {
            chain.doIntercept(ctx, mainHandler);
        } catch (AuthException e){
            StaticLog.error(e);
            ctx.status(e.getStatus().code);
        } catch (ValidatorException e){
            StaticLog.error(e);
            ctx.status(e.getCode());
        } catch (Throwable e) {
            StaticLog.error(e);
            ctx.status(500);
        }
    }
}